const { Sequelize, Model } = require('sequelize');
const { unset, clone, isArray } = require('lodash')
const {
    dbName,
    host,
    port,
    user,
    password
} = require('../config/config').database
const { httpHost } = require('../config/config')
const sequelize = new Sequelize(dbName, user, password, {
    dialect: 'mysql',
    host,
    port,
    logging: true, // 是否打印sql
    timezone: '+08:00', // 时区转为北京时间
    define: {

        timestamps: true, // 控制 创建  更新 
        paranoid: true,// 控制 删除 时间
        // 创建时间
        createdAt: 'created_at',
        //更新时间
        updatedAt: 'updated_at',
        //删除时间
        deletedAt: 'deleted_at',
        // 将驼峰 转成下划线  数据库名一般情况下
        underscored: true,
        // 定义排除字段
        scopes: {
            bh: {
                attributes: {
                    exclude: ['updated_at', 'deleted_at', 'created_at']
                }
            }

        }
    }
});

// 配出字段  js JSON.pase   toJSON
Model.prototype.toJSON = function () {
    // let data = this.dataValues
    let data = clone(this.dataValues)
    unset(data, 'updated_at')
    unset(data, 'created_at')
    unset(data, 'deleted_at')

    for (key in data) {
        if (key === 'image') {
            if (!data[key].startsWith('http'))
                data[key] = httpHost + data[key]
        }
    }

    if (isArray(this.exclude)) {
        this.exclude.forEach(
            (value) => {
                unset(data, value)
            }
        )
    }
    // this.exclude
    // exclude
    // a,b,c,d,e
    return data
}
// 自动生成数据表
sequelize.sync({
    force: false // true：自动删除表 重新创建
});

module.exports = { sequelize }

